package com.js.data.common.utils.excel;

import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;

import java.lang.reflect.Field;
import java.util.*;

/**
 * ExcelListener-excel监听类
 *
 * @author wujj
 * @version 1.0.0
 * @since 2020/6/17 18:31
 */
public class ExcelListener<T> extends AnalysisEventListener<T> {


    protected List<T> datas = Collections.synchronizedList(new ArrayList<>());

    /**
     * @param o 读取的每行数据
     * @author wujj
     * @since 2020/6/17 18:30
     */
    @Override
    public void invoke(T o, AnalysisContext analysisContext) {
        datas.add(o);
    }

    /**
     * 读取完之后的操作
     *
     * @param analysisContext
     * @author wujj
     * @since 2020/6/17 18:30
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }

    public List<T> getDatas() {
        return datas;
    }

    public void setDatas(List<T> datas) {
        this.datas = datas;
    }


    /**
     * 获取excel表头的内容，放入map，方便根据实体类对表头内容进行校验
     *
     * @param clazz 表头名称
     * @return 导入对象备注map
     * @throws NoSuchFieldException
     */
    public Map<Integer, String> getIndexNameMap(Class clazz) throws NoSuchFieldException {
        Map<Integer, String> result = new HashMap<>();
        Field field;
        Field[] fields = clazz.getDeclaredFields();
        for (Field item : fields) {
            field = clazz.getDeclaredField(item.getName());
            field.setAccessible(true);
            ExcelProperty excelProperty = field.getAnnotation(ExcelProperty.class);
            if (excelProperty != null) {
                int index = excelProperty.index();
                String[] values = excelProperty.value();
                StringBuilder value = new StringBuilder();
                for (String v : values) {
                    value.append(v);
                }
                result.put(index, value.toString());
            }
        }
        return result;
    }

}
